/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package admin.beans;

import imageProcessing.classes.GeneralBufferedImageMaker;
import ProcesamientoImagenes.interfaces.BufferedImageMaker;
import facades.CompanyFacade;
import facades.CompanySectorFacade;
import entities.Company;
import entities.CompanyOrder;
import entities.CompanySector;
import entities.Sector;
import facades.CompanyOrderFacade;
import facades.CompanyProductFacade;
import util.ImageStoreHelper;
import util.PrimeFacesBufferedImage;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.enterprise.context.SessionScoped;
import javax.enterprise.event.Event;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import org.primefaces.event.*;
import qualifiers.EditedEntityEvent;
/**
 *
 * @author MIsabel
 */
@Named(value = "adminEditCompanyBean")
@SessionScoped
public class AdminEditCompanyBean implements Serializable{
    
    @Inject
    private CompanyFacade companyEJB;
    @Inject
    private CompanySectorFacade companySectorEJB;
    private Company company;
    @Inject
    @EditedEntityEvent
    private Event<Company> updatedCompanyEvent;
    @Inject
    private CompanyOrderFacade companyOrderFacade;
    @Inject
    CompanyProductFacade companyProductFacade;
    private List<CompanyOrder> companyOrderList;
    private Sector selectedSector;
    private String oldLogo;
    private List<CompanySector> companySectorList;

    /**
     * Creates a new instance of CreateCompanyBean
     */
    public AdminEditCompanyBean() {

    }

    //@PostConstruct
    public String fillEditCompanyBean(Company company) {
        this.setCompany(company);
        companyOrderList = new ArrayList<CompanyOrder>();
        companySectorList = getCompany().getCompanySectorList();
        return "AdminEditCompanyView?faces-redirect=true";
    }

    public void reinitEditCompanyBean() {

    }

    public void editAndShowResponse() {
        Date date = new Date();
        getCompany().getIdUser().setLastDate(date);
        companyEJB.edit(getCompany());
        FacesContext context = FacesContext.getCurrentInstance();
        Locale locale = context.getViewRoot().getLocale();
        ResourceBundle rb = ResourceBundle.getBundle("messages", locale);
        String successMessage = rb.getString("UpdatedSuccessfully");
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, successMessage, successMessage);
        context.addMessage(null, message);
        context.renderResponse();
        updatedCompanyEvent.fire(getCompany());
    }

    public String editCompany() {
        Date date = new Date();
        getCompany().getIdUser().setLastDate(date);
        companyEJB.edit(getCompany());
        reinitEditCompanyBean();
        FacesContext context = FacesContext.getCurrentInstance();
        Locale locale = context.getViewRoot().getLocale();
        ResourceBundle rb = ResourceBundle.getBundle("messages", locale);
        String successMessage = rb.getString("UpdatedSuccessfully");
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, successMessage, successMessage);
        context.addMessage(null, message);
        context.renderResponse();
        setOldLogo(null);
        return null;
    }

    public void uploadLogo(FileUploadEvent event) throws IOException {
        BufferedImageMaker imageMaker = new GeneralBufferedImageMaker();
        BufferedImage originalSizeImage = imageMaker.getBufferedImageFromInputStream(event.getFile().getInputstream());
        Integer maxPixels = 750;
        PrimeFacesBufferedImage originalImageResized = new PrimeFacesBufferedImage(this.getScaledImage(originalSizeImage, maxPixels));
        setOldLogo(getCompany().getLogo());
        String fileName = ImageStoreHelper.storePersistentlyPrimeFacesBufferedImage(originalImageResized, getCompany());
        getCompany().setLogo(fileName);
    }
    
    public void cancelUploadLogo(){
        getCompany().setLogo(getOldLogo());
        setOldLogo(null);
    }

    //Mover todos los métodos getScaledImage a un helper cuando refactorice
    private BufferedImage getScaledImage(BufferedImage originalSizeImage, Integer maxPixels) {
        Integer originalWidt = new Integer(originalSizeImage.getWidth());
        Integer originalHeigh = new Integer(originalSizeImage.getHeight());
        Double originalWidth = originalWidt.doubleValue();
        Double originalHeight = originalHeigh.doubleValue();
        Double ratio = originalWidth / originalHeight;
        Integer resWidth = null;
        Integer resHeight = null;
        if (ratio > 1) {
            resWidth = maxPixels;
            resHeight = (int) Math.ceil(maxPixels / ratio);
        } else {
            resHeight = maxPixels;
            resWidth = (int) Math.ceil(maxPixels * ratio);
        }
        BufferedImage scaledImage = new BufferedImage(resWidth, resHeight, BufferedImage.TYPE_3BYTE_BGR);
        Graphics2D graphics2D = scaledImage.createGraphics();
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2D.drawImage(originalSizeImage, 0, 0, resWidth, resHeight, null);
        graphics2D.dispose();
        return scaledImage;
    }

    public void removeCompanySector(CompanySector removeSector) {
        if (removeSector != null) {
            companySectorList.remove(removeSector);
            companySectorEJB.remove(removeSector);
        }
    }

    public void addCompanySector() {
        CompanySector addSector = new CompanySector();
        addSector.setIdSector(selectedSector);
        addSector.setIdCompany(company);

        if (!getCompany().getCompanySectorList().contains(addSector)) {
            companySectorList.add(addSector);
            companySectorEJB.create(addSector);
        }
    }


    /**
     * @return the company
     */
    public Company getCompany() {
        return company;
    }

    /**
     * @param company the company to set
     */
    public void setCompany(Company company) {
        this.company = company;
    }

    /**
     * @return the selectedSector
     */
    public Sector getSelectedSector() {
        return selectedSector;
    }

    /**
     * @param selectedSector the selectedSector to set
     */
    public void setSelectedSector(Sector selectedSector) {
        this.selectedSector = selectedSector;
    }

    /**
     * @return the oldLogo
     */
    public String getOldLogo() {
        return oldLogo;
    }

    /**
     * @param oldLogo the oldLogo to set
     */
    public void setOldLogo(String oldLogo) {
        this.oldLogo = oldLogo;
    }
}
